/**
 * Tool API Routes
 *
 * Handles tool management (list, register, unregister)
 */

import { Hono } from 'hono';
import type { ApiResponse, ToolDefinition } from '@/types';
import { logger } from '@/utils/logger';
import { toolRegistry } from '@/tools/tool-factory';
import { builtinTools } from '@/tools/builtin';

export const toolRoutes = new Hono();

// Register built-in tools on module load
builtinTools.forEach(tool => toolRegistry.registerTool(tool));

/**
 * GET /api/tools
 *
 * List all registered tools
 */
toolRoutes.get('/', (c) => {
  const allTools = toolRegistry.getAllTools().map(tool => ({
    name: tool.name,
    description: tool.description,
    inputSchema: tool.inputSchema.shape,
  }));

  const response: ApiResponse = {
    success: true,
    data: allTools,
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * GET /api/tools/:name
 *
 * Get tool details
 */
toolRoutes.get('/:name', (c) => {
  const toolName = c.req.param('name');

  const tool = toolRegistry.getTool(toolName);

  if (!tool) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'TOOL_NOT_FOUND',
        message: `Tool ${toolName} not found`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 404);
  }

  const response: ApiResponse = {
    success: true,
    data: {
      name: tool.name,
      description: tool.description,
      inputSchema: tool.inputSchema.shape,
    },
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

/**
 * POST /api/tools/register
 *
 * Register a custom tool
 * Note: This endpoint is for registering tool metadata only.
 * The actual tool handler must be implemented server-side.
 */
toolRoutes.post('/register', async (c) => {
  try {
    const body = await c.req.json();
    const { name, description, inputSchema } = body;

    // Validate request
    if (!name || !description || !inputSchema) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'INVALID_REQUEST',
          message: 'Missing required fields: name, description, inputSchema',
        },
        timestamp: new Date().toISOString(),
      };
      return c.json(response, 400);
    }

    // Check if tool already exists
    if (toolRegistry.getTool(name)) {
      const response: ApiResponse = {
        success: false,
        error: {
          code: 'TOOL_ALREADY_EXISTS',
          message: `Tool ${name} already exists`,
        },
        timestamp: new Date().toISOString(),
      };
      return c.json(response, 409);
    }

    logger.info('Tool registration requested', { name });

    const response: ApiResponse = {
      success: true,
      data: {
        name,
        message: 'Tool metadata received. Implement handler server-side to complete registration.'
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response);
  } catch (error) {
    logger.error('Failed to register tool', error);

    const response: ApiResponse = {
      success: false,
      error: {
        code: 'TOOL_REGISTER_ERROR',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 500);
  }
});

/**
 * DELETE /api/tools/:name
 *
 * Unregister a tool
 * Note: Built-in tools cannot be unregistered
 */
toolRoutes.delete('/:name', (c) => {
  const toolName = c.req.param('name');

  // Check if tool exists
  const tool = toolRegistry.getTool(toolName);
  if (!tool) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'TOOL_NOT_FOUND',
        message: `Tool ${toolName} not found`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 404);
  }

  // Check if it's a built-in tool
  const isBuiltin = builtinTools.some(t => t.name === toolName);
  if (isBuiltin) {
    const response: ApiResponse = {
      success: false,
      error: {
        code: 'CANNOT_DELETE_BUILTIN',
        message: `Cannot delete built-in tool: ${toolName}`,
      },
      timestamp: new Date().toISOString(),
    };

    return c.json(response, 403);
  }

  logger.info('Tool unregistered', { name: toolName });

  const response: ApiResponse = {
    success: true,
    data: { name: toolName, deleted: true },
    timestamp: new Date().toISOString(),
  };

  return c.json(response);
});

